<template>
  <div class="article-detail">
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
    
    <div v-else-if="error" class="error">
      <h2>文章加载失败</h2>
      <p>{{ error }}</p>
      <button @click="goBack" class="back-btn">返回</button>
    </div>
    
    <div v-else-if="article" class="article-layout">
      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 文章头部 -->
        <div class="article-header">
          <div class="breadcrumb">
            <router-link to="/" class="breadcrumb-link">首页</router-link>
            <span class="breadcrumb-separator">></span>
            <span class="breadcrumb-current">文章预览</span>
          </div>
          
          <h1 class="article-title">{{ article.title }}</h1>
          
          <div class="article-meta">
            <div class="meta-item">
              <span class="meta-label">作者：</span>
              <span class="meta-value">{{ getAuthorName(article.authorId) }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">发布时间：</span>
              <span class="meta-value">{{ formatDate(article.createdAt) }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">状态：</span>
              <span class="meta-status" :class="article.status.toLowerCase()">
                {{ getStatusText(article.status) }}
              </span>
            </div>
          </div>
          
          <div class="article-actions">
            <button @click="goBack" class="action-btn secondary">
              <i class="fas fa-arrow-left"></i>
              返回
            </button>
            <button 
              v-if="canEdit" 
              @click="editArticle" 
              class="action-btn primary"
            >
              <i class="fas fa-edit"></i>
              编辑
            </button>
          </div>
        </div>
        
        <!-- 文章正文 -->
        <div class="article-body">
          <div class="content" v-html="renderMarkdown(article.content)"></div>
        </div>
        
        <!-- 文章底部标签 -->
        <div v-if="article.categories" class="article-footer">
          <div class="tags">
            <span 
              v-for="label in getCategoryLabels(article.categories)" 
              :key="label"
              class="tag"
            >
              {{ label }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ArrowLeft, Edit } from '@element-plus/icons-vue'
import { articleAPI } from '@api/article.js'
import { userAPI } from '@api/user.js'
import { dictAPI } from '@api/dict.js'
import { ElMessage } from 'element-plus'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'

export default {
  name: 'ArticlePreview',
  components: {
    ArrowLeft,
    Edit
  },
  data() {
    return {
      article: null,
      users: [],
      categories: [],
      loading: true,
      error: null
    }
  },
  computed: {
    currentUser() {
      return this.$store.state.user
    },
    canEdit() {
      return this.currentUser && 
             (this.currentUser.id === this.article?.authorId || this.currentUser.isAdmin)
    }
  },
  mounted() {
    this.loadArticle()
    this.loadUsers()
    this.loadCategories()
  },
  updated() {
    this.highlightCode()
  },
  methods: {
    async loadArticle() {
      this.loading = true
      this.error = null
      
      try {
        const articleId = this.$route.params.id
        const response = await articleAPI.getArticleById(articleId)
        
        if (response.data.success) {
          this.article = response.data.data
        } else {
          this.error = response.data.message || '文章不存在'
        }
      } catch (error) {
        console.error('加载文章失败:', error)
        this.error = '加载文章失败'
      } finally {
        this.loading = false
      }
    },
    
    async loadUsers() {
      try {
        const response = await userAPI.getAllUsers()
        if (response.data.success) {
          this.users = response.data.data
        }
      } catch (error) {
        console.error('加载用户失败:', error)
      }
    },
    
    async loadCategories() {
      try {
        const response = await dictAPI.getArticleCategories()
        if (response.data.success) {
          this.categories = response.data.data
        }
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    },
    
    getAuthorName(authorId) {
      if (!authorId) return '未知'
      const user = this.users.find(u => u.id === authorId)
      return user ? (user.fullName || user.username) : '未知'
    },
    
    getStatusText(status) {
      const statusMap = {
        'DRAFT': '草稿',
        'PUBLISHED': '已发布',
        'ARCHIVED': '已归档'
      }
      return statusMap[status] || status
    },
    
    getStatusType(status) {
      const typeMap = {
        'DRAFT': '',
        'PUBLISHED': 'success',
        'ARCHIVED': 'warning'
      }
      return typeMap[status] || ''
    },
    
    getCategoryLabels(categories) {
      if (!categories) return []
      const categoryList = categories.split(',').map(c => c.trim())
      return categoryList.map(categoryValue => {
        const category = this.categories.find(c => c.dictValue === categoryValue)
        return category ? category.dictLabel : categoryValue
      })
    },
    
    formatDate(dateString) {
      if (!dateString) return ''
      return new Date(dateString).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    renderMarkdown(content) {
      if (!content) return ''
      
      // 简单的Markdown到HTML转换
      let html = content
      
      // 处理标题
      html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>')
      html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>')
      html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>')
      
      // 处理代码块
      html = html.replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code class="language-$1">$2</code></pre>')
      html = html.replace(/`([^`]+)`/g, '<code>$1</code>')
      
      // 处理粗体和斜体
      html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      html = html.replace(/\*(.*?)\*/g, '<em>$1</em>')
      
      // 处理列表
      html = html.replace(/^- (.*$)/gim, '<li>$1</li>')
      html = html.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>')
      
      // 处理段落
      html = html.replace(/\n\n/g, '</p><p>')
      html = '<p>' + html + '</p>'
      
      return html
    },
    
    highlightCode() {
      this.$nextTick(() => {
        document.querySelectorAll('pre code').forEach((block) => {
          hljs.highlightElement(block)
        })
      })
    },
    
    goBack() {
      // 如果是从管理页面打开的，返回管理页面
      if (document.referrer && document.referrer.includes('/admin')) {
        window.close()
      } else {
        this.$router.go(-1)
      }
    },
    
    editArticle() {
      // 跳转到编辑页面
      this.$router.push(`/edit/${this.article.id}`)
    }
  }
}
</script>

<style scoped>
@import '@/styles/components/article.scss';

/* ArticlePreview 特有的样式 */
.article-detail {
  min-height: 100vh;
  padding: 0;
}

.article-layout {
  max-width: 1400px;
  padding: 2rem;
  gap: 0;
}
</style>
